/*
 * Copyright (c) 2007 Compl Yue Still, All Rights Reserved.
 */

package hbi.wire.java.host;

import java.io.IOException;
import java.lang.reflect.Array;
import java.nio.ByteBuffer;

class UntypedArray implements DataTag
{

    private Object values = null;

    public Object getTagValue()
    {
        return values;
    }

    public void reset()
    {
        values = null;
        elements = null;
    }

    private final Class<?> expectedType;

    UntypedArray(Class<?> expectedType)
    {
        assert expectedType.isArray();
        this.expectedType = expectedType;
    }

    private DataTagList elements = null;

    public boolean processIncomingData(ByteBuffer buffer) throws IOException
    {
        if (!buffer.hasRemaining()) return false;

        if (elements == null)
        {
            if (buffer.remaining() < 4) return false;
            int length = buffer.getInt();
            if (length < 0)
                throw new SecurityException("Too big array length.");
            if (length < 1)
            {
                if (this.expectedType == null)
                    values = new Object[0];
                else
                    values = Array.newInstance(this.expectedType
                        .getComponentType(), 0);
                return true;
            }
            if (this.expectedType == null)
                elements = new DataTagList(new Class<?>[length]);
            else
                elements = new DataTagList(expectedType.getComponentType(), length);
            if (!buffer.hasRemaining()) return false;
        }

        if (elements.processIncomingData(buffer))
        {
            values = elements.getTagValues();
            elements = null;
            return true;
        }

        return false;
    }

}
